import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import { Room } from './room.entity';

@Entity('participants')
@Index(['roomId', 'userId'], { unique: true })
@Index(['socketId'], { unique: true })
@Index(['joinedAt'])
export class Participant {
  @ApiProperty({ description: '参与者ID' })
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @ApiProperty({ description: '房间ID' })
  @Column({ type: 'uuid' })
  roomId: string;

  @ApiProperty({ description: '用户ID' })
  @Column({ type: 'varchar', length: 100 })
  userId: string;

  @ApiProperty({ description: 'Socket连接ID' })
  @Column({ type: 'varchar', length: 100, unique: true })
  socketId: string;

  @ApiProperty({ description: '用户昵称' })
  @Column({ type: 'varchar', length: 50, nullable: true })
  nickname?: string;

  @ApiProperty({ description: '用户头像URL' })
  @Column({ type: 'varchar', length: 500, nullable: true })
  avatar?: string;

  @ApiProperty({ description: '用户IP地址' })
  @Column({ type: 'varchar', length: 45 })
  ipAddress: string;

  @ApiProperty({ description: '用户代理信息' })
  @Column({ type: 'text', nullable: true })
  userAgent?: string;

  @ApiProperty({ description: '参与者角色' })
  @Column({
    type: 'enum',
    enum: ['host', 'participant'],
    default: 'participant',
  })
  role: 'host' | 'participant';

  @ApiProperty({ description: '连接状态' })
  @Column({
    type: 'enum',
    enum: ['connecting', 'connected', 'disconnected', 'reconnecting'],
    default: 'connecting',
  })
  status: 'connecting' | 'connected' | 'disconnected' | 'reconnecting';

  @ApiProperty({ description: '音频状态' })
  @Column({ type: 'boolean', default: true })
  audioEnabled: boolean;

  @ApiProperty({ description: '视频状态' })
  @Column({ type: 'boolean', default: true })
  videoEnabled: boolean;

  @ApiProperty({ description: '屏幕共享状态' })
  @Column({ type: 'boolean', default: false })
  screenShareEnabled: boolean;

  @ApiProperty({ description: '是否静音' })
  @Column({ type: 'boolean', default: false })
  isMuted: boolean;

  @ApiProperty({ description: '媒体设备信息' })
  @Column({ type: 'jsonb', nullable: true })
  mediaDevices?: {
    audioInputId?: string;
    videoInputId?: string;
    audioOutputId?: string;
    hasAudioInput?: boolean;
    hasVideoInput?: boolean;
  };

  @ApiProperty({ description: '网络质量信息' })
  @Column({ type: 'jsonb', nullable: true })
  networkQuality?: {
    rtt?: number; // 往返时间
    packetLoss?: number; // 丢包率
    bandwidth?: number; // 带宽
    quality?: 'excellent' | 'good' | 'fair' | 'poor';
    lastUpdated?: Date;
  };

  @ApiProperty({ description: '参与者元数据' })
  @Column({ type: 'jsonb', nullable: true })
  metadata?: {
    browser?: string;
    platform?: string;
    deviceType?: 'desktop' | 'mobile' | 'tablet';
    timezone?: string;
    language?: string;
    [key: string]: any;
  };

  @ApiProperty({ description: '加入时间' })
  @Column({
    type: 'timestamp with time zone',
    default: () => 'CURRENT_TIMESTAMP',
  })
  joinedAt: Date;

  @ApiProperty({ description: '离开时间' })
  @Column({ type: 'timestamp with time zone', nullable: true })
  leftAt?: Date;

  @ApiProperty({ description: '最后活动时间' })
  @Column({
    type: 'timestamp with time zone',
    default: () => 'CURRENT_TIMESTAMP',
  })
  lastActivityAt: Date;

  @ApiProperty({ description: '创建时间' })
  @CreateDateColumn()
  createdAt: Date;

  @ApiProperty({ description: '更新时间' })
  @UpdateDateColumn()
  updatedAt: Date;

  @ApiProperty({ description: '所属房间', type: () => Room })
  @ManyToOne(() => Room, room => room.participants, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'roomId' })
  room: Room;

  // 虚拟属性
  get isOnline(): boolean {
    return this.status === 'connected' || this.status === 'reconnecting';
  }

  get isHost(): boolean {
    return this.role === 'host';
  }

  get sessionDuration(): number {
    const endTime = this.leftAt || new Date();
    return Math.floor((endTime.getTime() - this.joinedAt.getTime()) / 1000);
  }

  get displayName(): string {
    return this.nickname || this.userId;
  }

  // 更新最后活动时间
  updateLastActivity(): void {
    this.lastActivityAt = new Date();
  }

  // 设置媒体状态
  setMediaState(audio: boolean, video: boolean): void {
    this.audioEnabled = audio;
    this.videoEnabled = video;
    this.updateLastActivity();
  }

  // 切换音频状态
  toggleAudio(): boolean {
    this.audioEnabled = !this.audioEnabled;
    this.updateLastActivity();
    return this.audioEnabled;
  }

  // 切换视频状态
  toggleVideo(): boolean {
    this.videoEnabled = !this.videoEnabled;
    this.updateLastActivity();
    return this.videoEnabled;
  }

  // 设置屏幕共享状态
  setScreenShare(enabled: boolean): void {
    this.screenShareEnabled = enabled;
    this.updateLastActivity();
  }

  // 设置静音状态
  setMuted(muted: boolean): void {
    this.isMuted = muted;
    this.updateLastActivity();
  }

  // 更新网络质量
  updateNetworkQuality(quality: Partial<Participant['networkQuality']>): void {
    this.networkQuality = {
      ...this.networkQuality,
      ...quality,
      lastUpdated: new Date(),
    };
    this.updateLastActivity();
  }

  // 离开房间
  leave(): void {
    this.leftAt = new Date();
    this.status = 'disconnected';
    this.updateLastActivity();
  }

  // 重新连接
  reconnect(newSocketId: string): void {
    this.socketId = newSocketId;
    this.status = 'connected';
    this.leftAt = null;
    this.updateLastActivity();
  }
}
